<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showFailToast, showLoadingToast, closeToast } from 'vant'

interface MedicalGuideDetail {
  medicalGuideId: number
  theme: string
  medicalGuideName: string
  dayDateTime: string
  viewer: number
  details: string
}

interface ApiResponse {
  mes: string
  code: number
  data: MedicalGuideDetail[]
}

const router = useRouter()
const route = useRoute()

// 指南详情数据
const guideDetail = ref<MedicalGuideDetail>({
  medicalGuideId: 0,
  theme: '',
  medicalGuideName: '',
  dayDateTime: '',
  viewer: 0,
  details: ''
})

const loading = ref(false)

// 获取指南详情
const fetchGuideDetail = async () => {
  try {
    loading.value = true
    showLoadingToast({
      message: '加载中...',
      forbidClick: true
    })

    const medicalGuideId = route.params.id as string

    if (!medicalGuideId) {
      showFailToast('指南ID不存在')
      router.back()
      return
    }

    const response = await fetch(`http://localhost:5104/api/Healthing/FanMedical?MedicalGuideId=${medicalGuideId}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'accept': 'text/plain'
      }
    })

    if (!response.ok) {
      throw new Error('网络请求失败')
    }

    const result: ApiResponse = await response.json()

    if (result.code === 300 && result.data && result.data.length > 0 && result.data[0]) {
      guideDetail.value = result.data[0]
    } else {
      showFailToast(result.mes || '获取指南详情失败')
      router.back()
    }
  } catch (error) {
    console.error('获取指南详情失败:', error)
    showFailToast('网络请求失败，请检查网络连接')
    router.back()
  } finally {
    loading.value = false
    closeToast()
  }
}

// 格式化日期
const formatDate = (dateString: string) => {
  try {
    const date = new Date(dateString)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  } catch (error) {
    return dateString.split('T')[0]
  }
}

// 格式化详情内容 - 处理换行和分段
const formatDetails = (details: string) => {
  if (!details) return ''
  
  // 将 \r\n 转换为换行，并处理多个连续换行
  return details
    .replace(/\r\n/g, '\n')
    .replace(/\n{3,}/g, '\n\n') // 将3个或更多连续换行替换为2个
    .trim()
}

// 初始化
onMounted(() => {
  fetchGuideDetail()
})
</script>

<template>
  <div class="guide-detail-view">
    <!-- 导航栏 -->
    <van-nav-bar
      title="指南详情"
      left-text=""
      left-arrow
      @click-left="router.back()"
      class="nav-bar"
    >
      <template #right>
        <van-icon name="ellipsis" size="18" />
        <van-icon name="aim" size="18" style="margin-left: 12px" />
      </template>
    </van-nav-bar>

    <!-- 内容区域 -->
    <div class="content-wrapper">
      <!-- 标题和元数据 -->
      <div class="guide-header">
        <h1 class="guide-title">{{ guideDetail.medicalGuideName }}</h1>
        <div class="guide-meta">
          <span class="guide-date">{{ formatDate(guideDetail.dayDateTime) }}</span>
          <span class="guide-viewer">{{ guideDetail.viewer }}人已查看</span>
        </div>
      </div>

      <!-- 详情内容 -->
      <div class="guide-content">
        <div v-if="loading" class="loading-state">
          加载中...
        </div>
        <div v-else-if="guideDetail.details" class="details-content">
          <div class="details-text">{{ formatDetails(guideDetail.details) }}</div>
        </div>
        <div v-else class="empty-state">
          暂无内容
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.guide-detail-view {
  width: 100%;
  min-height: 100vh;
  background-color: #fff;
}

.nav-bar {
  background-color: #fff;
  border-bottom: 1px solid #ebedf0;
}

.content-wrapper {
  padding: 16px;
}

/* 标题和元数据 */
.guide-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebedf0;
}

.guide-title {
  font-size: 20px;
  font-weight: bold;
  color: #323233;
  margin: 0 0 12px 0;
  line-height: 1.5;
}

.guide-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 14px;
  color: #969799;
}

.guide-date {
  color: #969799;
}

.guide-viewer {
  color: #969799;
}

/* 详情内容 */
.guide-content {
  margin-top: 0;
  padding-top: 16px;
}

.loading-state,
.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #969799;
  font-size: 14px;
}

.details-content {
  line-height: 1.8;
  color: #323233;
}

.details-text {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  font-size: 15px;
  line-height: 1.8;
  color: #323233;
  white-space: pre-wrap;
  word-wrap: break-word;
  margin: 0;
  padding: 0;
  background: transparent;
  border: none;
}

/* 优化段落间距和显示 */
.details-text {
  margin-bottom: 0;
  padding-bottom: 20px;
}

/* 保留原文本格式 */
.details-text {
  white-space: pre-wrap;
  word-break: break-word;
}
</style>
